package com.example.skyline.aspect;


import com.example.skyline.entity.Log;

import com.example.skyline.service.ILogService;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 系统日志切面
 */
@Aspect
@Component
@Slf4j
public class LogAspect {
    
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private ILogService logService;
    
    /**
     * 定义切点：拦截所有标注了@LogAnnotation的方法
     */
    @Pointcut("@annotation(com.example.skyline.annotation.LogAnnotation)")
    public void logPointCut() {}
    
    /**
     * 定义切点：拦截controller包下的所有方法
     */
    @Pointcut("execution(* com.example.skyline.controller..*.*(..))")

    public void controllerPointCut() {}
    
    /**
     * 环绕通知：记录操作日志
     */
    @Around("logPointCut() || controllerPointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 生成唯一请求ID
        String traceId = UUID.randomUUID().toString();
        
        // 获取方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        
        // 创建日志对象
        Log operationLog = new Log();
        operationLog.setTraceId(traceId);
        operationLog.setMethod(signature.getName());
        operationLog.setClassName(joinPoint.getTarget().getClass().getName());
        operationLog.setOperateTime(LocalDateTime.now());
        
        // 获取请求参数
        Object[] args = joinPoint.getArgs();
        if (args != null && args.length > 0) {
            try {
                String params = Arrays.stream(args)
                        .filter(arg -> !(arg instanceof HttpServletRequest))
                        .map(arg -> {
                            try {
                                return objectMapper.writeValueAsString(arg);
                            } catch (Exception e) {
                                return arg.toString();
                            }
                        })
                        .collect(Collectors.joining(", "));
                operationLog.setParams(params);
            } catch (Exception e) {
                operationLog.setParams("参数解析失败");
            }
        }
        
        // 获取请求信息
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) 
                    RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                operationLog.setIp(getIpAddress(request));
                
                // 从请求头或session中获取用户信息
                // operationLog.setUserId(...);
                // operationLog.setUsername(...);
                // operationLog.setRole(...);
            }
        } catch (Exception e) {
            log.error("获取请求信息失败", e);
        }
        
        // 执行目标方法并计算耗时
        long startTime = System.currentTimeMillis();
        Object result = null;
        try {
            result = joinPoint.proceed();
            operationLog.setResult("SUCCESS");
        } catch (Throwable throwable) {
            operationLog.setResult("FAILURE");
            operationLog.setErrorMsg(throwable.getMessage());
            throw throwable;
        } finally {
            long endTime = System.currentTimeMillis();
            operationLog.setCostTime(endTime - startTime);

            logService.insert(operationLog);
            // 记录日志
            log.info("操作日志: {}", objectMapper.writeValueAsString(operationLog));
        }
        
        return result;
    }
    
    /**
     * 异常通知：捕获并记录异常日志
     */
    @AfterThrowing(pointcut = "logPointCut() || controllerPointCut()", throwing = "ex")
    public void afterThrowing(Throwable ex) {
        log.error("系统异常: ", ex);
    }
    
    /**
     * 获取客户端IP地址
     */
    private String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}